package cn.bellychang.leetcode.question024;

/**
 * @author ChangLiang
 * @date 2021/3/16
 */
public class Solution {

    public ListNode swapPairs(ListNode head) {
        if(head == null) return null;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode beforeNode = head;
        ListNode afterNode = head.next;
        ListNode tail = dummy;
        while(beforeNode!= null && afterNode!=null){
            // swap
            beforeNode.next = afterNode.next;
            afterNode.next = beforeNode;
            tail.next = afterNode;
            // 移动tail
            tail = beforeNode;
            beforeNode = tail.next;
            if(beforeNode == null) break;
            afterNode = beforeNode.next;
        }
        return dummy.next;
    }
}
